﻿using Serilog;
using sh3h.chuansha.job.Domain.Entities;
using sh3h.chuansha.job.SqlSugarCore;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;

namespace sh3h.chuansha.job.Jobs
{
    public class SynWTBApprovalStatusJob : BackgroundService
    {
        private readonly IConfiguration configuration;

        private readonly ISqlSugarClient db;

        public SynWTBApprovalStatusJob(IConfiguration _configuration, ISqlSugarClient _db)
        {
            configuration = _configuration;
            db = _db;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    Serilog.Log.Information("SynWTBApprovalStatusJob running at: {time}", DateTimeOffset.Now);
                    Serilog.Log.Information("SynWTBApprovalStatusJob begin");
                    await synVoid();
                    await Task.Delay(1000 * 60 * 5, stoppingToken);
                }
            }
            catch (OperationCanceledException)
            {
                // When the stopping token is canceled, for example, a call made from services.msc,
                // we shouldn't exit with a non-zero exit code. In other words, this is expected...
            }
            catch (Exception ex)
            {
                Serilog.Log.Error(ex, $" SynHotlineFileJob {ex.Message}");

                // Terminates this process and returns an exit code to the operating system.
                // This is required to avoid the 'BackgroundServiceExceptionBehavior', which
                // performs one of two scenarios:
                // 1. When set to "Ignore": will do nothing at all, errors cause zombie services.
                // 2. When set to "StopHost": will cleanly stop the host, and log errors.
                //
                // In order for the Windows Service Management system to leverage configured
                // recovery options, we need to terminate the process with a non-zero exit code.
                Environment.Exit(1);
            }
        }

        private async Task synVoid()
        {
            try
            {
                YWTB_WS.YWTB_WSSoapClient client = new YWTB_WS.YWTB_WSSoapClient(YWTB_WS.YWTB_WSSoapClient.EndpointConfiguration.YWTB_WSSoap);
                // 没回填
                var mhts = SqlSugarDBContext.Db.Queryable<WTBYeWuZB>()
                        .Where(u => u.I_ZHUANGTAI == 1 && u.D_JIESHOUSJ > DateTime.Now.AddDays(-10)).ToList();
                foreach (var item in mhts)
                {
                    try
                    {
                        List<WF_PROJECTINFO> liuchengs = SqlSugarDBContext.Db.Queryable<WF_PROJECTINFO>()
                                .Where(u => u.S_BEIZHU == item.INCIDENT_ID).ToList();
                        if (liuchengs.Where(u => u.I_ZHUANGTAI == 4 || u.I_ZHUANGTAI == 2).Count() > 0)
                        {
                            item.I_ZHUANGTAI = 3;
                            item.D_HUITIANSJ = DateTime.Now;
                            SqlSugarDBContext.Db.Updateable(item).ExecuteCommand();

                        }
                    }
                    catch (Exception ex)
                    { 
                    }
                }
                var synStatusList = SqlSugarDBContext.Db.Queryable<WTBYeWuZB>()
                    .Where(u => u.D_HUITIANSJ > DateTime.Now.AddDays(-5)
                 && u.I_ZHUANGTAI == 3 && (u.I_JOBSYNCOUNT <= 5 || u.I_JOBSYNCOUNT == null)).ToList();

                foreach (var item in synStatusList)
                {
                    string serialNumber = "";
                    try
                    {
                        Serilog.Log.Information("synVoid INCIDENT_ID:" + item.INCIDENT_ID);
                        if (item.INCIDENT_TYPE == "McsItemType.ResidentUnionTransfer")
                        {
                            //同步合同
                            try
                            {
                                var a = client.UploadHeTongNEW(item.INCIDENT_ID);
                                Serilog.Log.Information("UploadHeTongNEW res:" + a);
                            }
                            catch (Exception ex)
                            {

                                Serilog.Log.Error(ex, "UploadHeTongNEW error:");
                            }
                        }
                        //同步状态
                        //同步合同
                        try
                        {
                            string leixing = item.BUSINESS_TYPE;
                            var bodyObj = new
                            {
                                incident_id = item.INCIDENT_ID,
                                shw_company = "PDXQZLS",
                                oper_id = item.S_HUITIANR,
                                status = "IncidentStatus.Finish",
                                result = "01",
                                description = ""
                            };

                            string strBody = JsonSerializer.Serialize(bodyObj, new JsonSerializerOptions()
                            {
                                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                            });

                            var a = client.updateIncidentStatus(leixing, strBody);
                            Serilog.Log.Information("updateIncidentStatus res:" + a);
                        }
                        catch (Exception ex)
                        {
                            Serilog.Log.Error(ex, "updateIncidentStatus error:");

                        }


                    }
                    catch (Exception ex)
                    {
                        Log.Information(serialNumber + " error :" + ex.Message.ToString());

                    }
                    item.I_JOBSYNCOUNT = item.I_JOBSYNCOUNT + 1;

                    SqlSugarDBContext.Db.Updateable(item).ExecuteCommand();

                }
            }
            catch (Exception ex)
            {
                Log.Information("SynHotlineFileJob error :" + ex.Message.ToString());
            }


        }
    }
}
